﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fis.Web.Rules.Book
{
    public class SynchronizeRule : DynamicRule
    {
        void OneTableAll()
        {
            var name = Paramater["ONETABLEALL"].ToString();
            var data = Model.QueryTable(name);
            if (data.Rows.Count > 0)
                Result["ONETABLEALL"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(data);
            Status = 1;
        }

        public override void ExecuteNonTrans()
        {

            if (Paramater.ContainsKey("ONETABLEALL"))
            {
                OneTableAll();
                return;
            }



            var xml = Agile.Engine.ObjectContext.GetResource("BookResource");

            var tables = xml.GetString("sync_tables");

            var da = new Agile.Engine.Data.DataAccess() { Context = Model.DataContext };
            var dic = new System.Collections.Hashtable();
            Result["SyncDate"] = DateTime.Now;

            //同步数据
            foreach (var i in tables.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                da.TableName = i.Trim();
                var dt = da.Query(string.Format("SINDEXDATE>='{0}'", Paramater["SyncDate"]));
                if (dt.Rows.Count > 0)
                {
                    dic[da.TableName] = Agile.Engine.Utils.ZipUtils.ZipDataTable(dt);
                }
            }

            //同步已删除数据
            var delete = Model.QueryTable("TXTRA", string.Format("SINDEXDATE>='{0}' AND FXTRA5=1", Paramater["SyncDate"]));
            if (delete.Rows.Count > 0)
                dic["DeleteInfo"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(delete);

            //同步反结帐信息
            var reset = Model.QueryTable("TXTRA", string.Format("SINDEXDATE>='{0}' AND FXTRA5=2", Paramater["SyncDate"]));
            if (reset.Rows.Count > 0)
                dic["Reset"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(reset);

            //同步初始导入信息
            var import = Model.QueryTable("TXTRA", string.Format("SINDEXDATE>='{0}' AND FXTRA5=3", Paramater["SyncDate"]));
            if (reset.Rows.Count > 0)
                dic["Import"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(reset);
            var version = new Fis.Web.Rules.Entry.VersionUpdate();

            if (version.HasNewVersion(Version))
            {
                dic["NewVersion"] = Agile.Engine.Utils.ZipUtils.Zip(version.NewVersion);
            }


            if (dic.Count > 0)
            {
                Result["data"] = dic;
            }

            Status = 1;
        }
    }
}
